package com.loe.logger

import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import com.google.android.material.bottomsheet.BottomSheetDialog
import kotlinx.android.synthetic.main.logger_environment_dialog.view.*

/**
 * 切换web环境弹框
 *
 * @author zls
 * @since 2025/6/12
 */
class LoggerWebEnvironmentDialog(private val activity: FragmentActivity)
{
    private val dialog: BottomSheetDialog
    private var isInit = false
    private lateinit var rootView: ViewGroup

    private var onSelect: ((EnvironmentBean) -> Unit)? = null

    init
    {
        dialog = BottomSheetDialog(activity)
    }

    fun show(onSelect: ((EnvironmentBean) -> Unit))
    {
        this.onSelect = onSelect
        if (!dialog.isShowing)
        {
            val window = dialog.window
            if (!isInit && window != null)
            {
                dialog.setContentView(R.layout.logger_environment_dialog)
                window.setBackgroundDrawableResource(android.R.color.transparent)
                val bottomSheet = dialog.delegate.findViewById<View>(R.id.design_bottom_sheet)
                bottomSheet?.setBackgroundResource(android.R.color.transparent)
                rootView = window.decorView as ViewGroup
                rootView.setPadding(0, 0, 0, 0)
                isInit = true
            }
            dialog.show()
            onShow()
        }
    }

    private fun onShow()
    {
        val adapter = LoggerEnvironmentAdapter(activity, LoeLogger.staticWebEnvironmentList, "web")
        adapter.setOnResetListener()
        {
            onSelect?.invoke(LoeLogger.staticWebEnvironmentList[0])
        }
        rootView.listView.adapter = adapter

        rootView.listView.setOnItemClickListener()
        { adapterView, view, i, l ->
            val bean = adapter.getItem(i) as EnvironmentBean
            onSelect?.invoke(bean)
            dialog.dismiss()
        }

        rootView.buttonAdd.setOnClickListener()
        {
            LoggerAddEnvironmentDialog(activity).show()
            { type, baseUrl ->
                adapter.addBean(type, baseUrl)
            }
        }

        rootView.buttonCancel.setOnClickListener()
        {
            dialog.dismiss()
        }
    }
}